package com.vc.commons.interceptor;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 默认的拦截器
 * @author Cris
 *
 */
@Component
public class DefaultInterceptorHandler implements HandlerInterceptor {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	private final static String REQUEST_START_TIME = "requestStartTime";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 只有返回true才会继续向下执行，返回false取消当前请求
		System.out.println("请求到了");
		request.setAttribute(REQUEST_START_TIME, new Date().getTime());
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println("请求结束");
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		Long startTime = (Long) request.getAttribute(REQUEST_START_TIME);
		
		logger.info("SPEND TIME : " + (new Date().getTime() - startTime));
	}

}
